
package GUILayer;

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Calendar extends JFrame{
	static JLabel labelMonth, labelYear;
	static JButton btPrev, btNext;
	static JTable tableCalendar;
	static JComboBox comboBoxYear;

	static Container pane;
	static DefaultTableModel tableModelCalendar; //Table model
	static JScrollPane scrolPaneCalendar; //The scrollpane
	static JPanel jCalendar;
	static int realYear, realMonth, realDay, currentYear, currentMonth;
	static String selectedDate;
	static boolean dateSelected;
	private JTextField labelFromTheParrentFrame;

	public Calendar(final JTextField labelFromTheParrentFrame){
		//Look and feel
		try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
            setIconImage(Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("b4/advancedgui/menu/resources/green_arrow_right.png")));
        } catch (Exception ex) {
            Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
           
        }

		
	setSize(330, 375); //Set size to 400x400 pixels
		pane = getContentPane(); //Get content pane
		pane.setLayout(null); //Apply null layout
		setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); //Close when X is clicked
		dateSelected=false;
		//Create controls
		labelMonth = new JLabel ("January");
		labelYear = new JLabel ("Change year:");
		comboBoxYear = new JComboBox();
		btPrev = new JButton ("<<");
		btNext = new JButton (">>");
		tableModelCalendar = new DefaultTableModel(){public boolean isCellEditable(int rowIndex, int mColIndex){return false;}};
		tableCalendar = new JTable(tableModelCalendar);
		scrolPaneCalendar = new JScrollPane(tableCalendar);
		jCalendar = new JPanel(null);
		this.labelFromTheParrentFrame=labelFromTheParrentFrame;
		setTitle("Choose Date");

		//Set border
		jCalendar.setBorder(BorderFactory.createTitledBorder("Calendar"));
		
		//Register action listeners
		btPrev.addActionListener(new btnPrev_Action());
		btNext.addActionListener(new btnNext_Action());
		comboBoxYear.addActionListener(new cmbYear_Action());
		
		//Add controls to pane
		pane.add(jCalendar);
		jCalendar.add(labelMonth);
		jCalendar.add(labelYear);
		jCalendar.add(labelYear);
		jCalendar.add(btPrev);
		jCalendar.add(btNext);
		jCalendar.add(scrolPaneCalendar);
		jCalendar.add(comboBoxYear);
		//Set bounds
		jCalendar.setBounds(0, 0, 320, 335);
		labelMonth.setBounds(160-labelMonth.getPreferredSize().width/2, 25, 100, 25);
		labelYear.setBounds(140, 305, 80, 20);
		comboBoxYear.setBounds(230, 305, 80, 20);
		btPrev.setBounds(10, 25, 50, 25);
		btNext.setBounds(260, 25, 50, 25);
		scrolPaneCalendar.setBounds(10, 50, 300, 250);
		
		//Make frame visible
		setResizable(false);
		setVisible(true);
		
		//Get real month/year
		GregorianCalendar cal = new GregorianCalendar(); //Create calendar
		realDay = cal.get(GregorianCalendar.DAY_OF_MONTH); //Get day
		realMonth = cal.get(GregorianCalendar.MONTH); //Get month
		realYear = cal.get(GregorianCalendar.YEAR); //Get year
		currentMonth = realMonth; //Match month and year
		currentYear = realYear;
		
		//Add headers
		String[] headers = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; //All headers
		for (int i=0; i<7; i++){
			tableModelCalendar.addColumn(headers[i]);
		}
		
		tableCalendar.getParent().setBackground(tableCalendar.getBackground()); //Set background

		//No resize/reorders
		tableCalendar.getTableHeader().setResizingAllowed(false);
		tableCalendar.getTableHeader().setReorderingAllowed(false);

		//Single cell selection

	    tableCalendar.setCellSelectionEnabled(true);
		tableCalendar.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		tableCalendar.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
		      public void valueChanged(ListSelectionEvent e) {
		    
		        

		      }

		    });

		//Set row/column count
		tableCalendar.setRowHeight(38);
		
		JButton btnOk = new JButton("OK");
		btnOk.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				System.out.println(selectedDate);
				labelFromTheParrentFrame.setText(selectedDate);
				dispose();
			}
		});
		btnOk.setBounds(20, 304, 89, 23);
		jCalendar.add(btnOk);
		tableModelCalendar.setColumnCount(7);
		tableModelCalendar.setRowCount(6);
		
		//Populate table
		for (int i=realYear-100; i<=realYear+100; i++){
			comboBoxYear.addItem(String.valueOf(i));
		}
		
		//Refresh calendar
		refreshCalendar (realMonth, realYear); //Refresh calendar
	}
	
	public static void refreshCalendar(int month, int year){
		//Variables
		String[] months =  {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
		int nod, som; //Number Of Days, Start Of Month
			
		//Allow/disallow buttons
		btPrev.setEnabled(true);
		btNext.setEnabled(true);
		if (month == 0 && year <= realYear-10){btPrev.setEnabled(false);} //Too early
		if (month == 11 && year >= realYear+100){btNext.setEnabled(false);} //Too late
		labelMonth.setText(months[month]); //Refresh the month label (at the top)
		labelMonth.setBounds(160-labelMonth.getPreferredSize().width/2, 25, 180, 25); //Re-align label with calendar
		comboBoxYear.setSelectedItem(String.valueOf(year)); //Select the correct year in the combo box
		
		//Clear table
		for (int i=0; i<6; i++){
			for (int j=0; j<7; j++){
				tableCalendar.setValueAt(null, i, j);
			}
		}
		
		//Get first day of month and number of days
		GregorianCalendar cal = new GregorianCalendar(year, month, 1);
		nod = cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
		som = cal.get(GregorianCalendar.DAY_OF_WEEK);
		
		//Draw calendar
		for (int i=1; i<=nod; i++){
			int row = new Integer((i+som-2)/7);
			int column  =  (i+som-2)%7;
			tableCalendar.setValueAt(i, row, column);
		}

		//Apply renderers
		tableCalendar.setDefaultRenderer(tableCalendar.getColumnClass(0), new tblCalendarRenderer());
	}

	static class tblCalendarRenderer extends DefaultTableCellRenderer{
		public Component getTableCellRendererComponent (JTable table, Object value, boolean selected, boolean focused, int row, int column){
			super.getTableCellRendererComponent(table, value, selected, focused, row, column);
			if (column == 0 || column == 6){ //Week-end
				setBackground(new Color(255, 220, 220));
			}
			else{ //Week
				setBackground(new Color(255, 255, 255));
			}
			
		   if(selected)
		   {
			   setBackground(new Color(220, 220, 255));
			   selectedDate=currentYear+"-"+(currentMonth+1)+"-"+value;
			   System.out.println(value);
		   }
            
		   else
			 if (value != null){
				if (Integer.parseInt(value.toString()) == realDay && currentMonth == realMonth && currentYear == realYear){ //Today
					setBackground(new Color(152,251,152));
				}
			}
			setBorder(null);
			setForeground(Color.black);
			return this;  
		}
	}

	static class btnPrev_Action implements ActionListener{
		public void actionPerformed (ActionEvent e){
			if (currentMonth == 0){ //Back one year
				currentMonth = 11;
				currentYear -= 1;
			}
			else{ //Back one month
				currentMonth -= 1;
			}
			refreshCalendar(currentMonth, currentYear);
		}
	}
	static class btnNext_Action implements ActionListener{
		public void actionPerformed (ActionEvent e){
			if (currentMonth == 11){ //Foward one year
				currentMonth = 0;
				currentYear += 1;
			}
			else{ //Foward one month
				currentMonth += 1;
			}
			refreshCalendar(currentMonth, currentYear);
		}
	}
	static class cmbYear_Action implements ActionListener{
		public void actionPerformed (ActionEvent e){
			if (comboBoxYear.getSelectedItem() != null){
				String b = comboBoxYear.getSelectedItem().toString();
				currentYear = Integer.parseInt(b);
				refreshCalendar(currentMonth, currentYear);
			}
		}
	}
}
